//
//  JDOrderDetailViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/5/10.
//

import UIKit
import SwiftyJSON
/// 订单详情
class JDOrderDetailViewController: JDBaseViewController {

    var orderType: JDOrderType = .waitingPay
    var shopName: String?
    var orderId: String?
    
    var bottomToolBarContainerView: UIView?
    var tipsLabel: UILabel?
    var totalPriceTitle: UILabel?
    var totalPriceLabel: UILabel?
    var cancelButton: UIButton?
    var continuePaymentButton: UIButton?
    
    var mainTableView: UITableView?
    var goodsDetailModel: JDOrderDetailModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupConfig()
        self.setupUIElements()
        self.getNetData()
        self.refreshByType()
        // Do any additional setup after loading the view.
//        self?.simpleCallBack?()
        NotificationCenter.default.addObserver(self, selector: #selector(payResult(_:)), name: NSNotification.Name("payResult"), object: nil)
    }
    
    
    @objc func payResult(_ notify: NSNotification) {
        print("处理支付结果222")
        let payResultType = notify.object as? String
        if payResultType == "成功" {
            let resultVC = JDPayResultViewController()
            resultVC.paySuccess = true
            self.hidesBottomBarPushViewController(resultVC)
            
        } else if payResultType == "失败" {
            let resultVC = JDPayResultViewController()
            resultVC.paySuccess = false
            self.hidesBottomBarPushViewController(resultVC)
            
        } else if payResultType == "取消" {
            let resultVC = JDPayResultViewController()
            resultVC.paySuccess = false
            resultVC.resultLabel?.text = "用户取消"
            self.hidesBottomBarPushViewController(resultVC)
        }
        
        print("处理结果吧")
        
    }
    
    
    func setupConfig() {
        self.setupNavigationTitle("订单详情")
        self.setupLeftBackItem()
    }
    
    func setupUIElements() {
        
        self.bottomToolBarContainerView = UIView()
        self.view.addSubview(self.bottomToolBarContainerView!)
        self.bottomToolBarContainerView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(76)
        })
        self.bottomToolBarContainerView?.backgroundColor = .white

        self.totalPriceTitle = UILabel()
        self.bottomToolBarContainerView?.addSubview(self.totalPriceTitle!)
        totalPriceTitle?.snp.makeConstraints { make in
            make.left.equalTo(self.bottomToolBarContainerView!).offset(12)
            make.centerY.equalTo(self.bottomToolBarContainerView!)
        }
        totalPriceTitle?.text = "合计:"
        totalPriceTitle?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 1)
        
        self.totalPriceLabel = UILabel()
        self.bottomToolBarContainerView?.addSubview(self.totalPriceLabel!)
        self.totalPriceLabel?.snp.makeConstraints({ make in
            make.left.equalTo(self.totalPriceTitle!.snp.right)
            make.bottom.equalTo(self.totalPriceTitle!)
        })
        self.totalPriceLabel?.text = "￥0.00"
        self.totalPriceLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 20, weight: .semibold), textColor: color("#FA6161"))
        
        self.continuePaymentButton = UIButton(type: .custom)
        self.bottomToolBarContainerView?.addSubview(self.continuePaymentButton!)
        self.continuePaymentButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomToolBarContainerView!).offset(-12)
            make.centerY.equalTo(self.bottomToolBarContainerView!).offset(-5)
            make.size.equalTo(CGSize(width: 105, height: 40))
        })
        self.continuePaymentButton?.layer.cornerRadius = 20
        self.continuePaymentButton?.backgroundColor = color("#FA6161")
        self.continuePaymentButton?.setTitle("继续付款", for: .normal)
        self.continuePaymentButton?.setTitleColor(.white, for: .normal)
        self.continuePaymentButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.continuePaymentButton?.addTarget(self, action: #selector(continuePayAction), for: .touchUpInside)
        
        self.cancelButton = UIButton(type: .custom)
        self.bottomToolBarContainerView?.addSubview(self.cancelButton!)
        self.cancelButton?.snp.makeConstraints({ make in
            make.right.equalTo(self.bottomToolBarContainerView!).offset(-129)
            make.centerY.equalTo(self.bottomToolBarContainerView!).offset(-5)
            make.size.equalTo(CGSize(width: 105, height: 40))
        })
        self.cancelButton?.layer.cornerRadius = 20
        self.cancelButton?.backgroundColor = color("#F5F6F8")
        self.cancelButton?.setTitle("取消订单", for: .normal)
        self.cancelButton?.setTitleColor(color("#8D9198"), for: .normal)
        self.cancelButton?.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        self.cancelButton?.addTarget(self, action: #selector(cancelOrderAction(_:)), for: .touchUpInside)
        
        self.tipsLabel = UILabel()
        self.view.addSubview(self.tipsLabel!)
        self.tipsLabel?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.bottomToolBarContainerView!.snp.top)
            make.height.equalTo(38)
        })
        self.tipsLabel?.backgroundColor = color("#333333").withAlphaComponent(0.8)
        self.tipsLabel?.text = "5分钟后订单关闭，请尽快完成支付"
        self.tipsLabel?.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: .white)

//        JDSettlementTableViewCell
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.tipsLabel!.snp.top)//.offset(-25)
        })
        self.mainTableView?.register(JDOrderDetailCell.self, forCellReuseIdentifier: "myCell")
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.backgroundColor = self.commonColor
        self.mainTableView?.separatorStyle = .none
    }
    
    
    //    1:"买家待付款"
    //    2:"未付款自动取消"
    //    3:"已付款(待接单)"
    //    4:"买家手动取消"
    //    5:"商家已接单"
    //    6:"商家已拒单"
    //    7:"商家已发货"
    //    8:"物流已到货"
    //    9:"买家确认收货"
    
    func getNetData() {
        var params = [String: Any]()
        params["orderId"] = self.orderId
        
        if self.orderType == .waitingPay {
            // 待付款
        } else if self.orderType == .alreadyPay {
            // 已接单
        } else if self.orderType == .pickup {
            // 待取货
        } else if self.orderType == .completed {
            // 已完成
        } else if self.orderType == .refusse {
            // 已拒单
        }
        
        JDNetWorkRequest(.getOrderDetailInfo(params)) { responseStr in
//            {"msg":"ok","data":{"id":12,"orderTime":"2024-08-20 13:33:48","totalAmount":150000,"customerServicePhone":"0411-87979988","mobile":"13284231123","province":"辽宁省","freight":7500,"buyerName":"朱","orderNo":"JDCB1724132028350","receiverName":"朱","address":"华北路大湾市场","orderStatus":1,"city":"大连市","district":"甘井子区","postal":"116000","tariff":13500,"userMessage":"789","goodsList":[{"origin":"日本","goodsSpecificationNameList":[],"goodsName":"黑眼镜","goodsId":1,"goodsSpecificationIdList":[],"goodsBrand":"上下一白","goodsPriceText":"750.00","goodsMainImageUrl":"https:\/\/img11.360buyimg.com\/n1\/s450x450_jfs\/t1\/54403\/16\/24313\/48223\/669b4cd9F1f1e51e2\/91cdf0091dec0c68.jpg","goodsSkuId":1,"goodsPrice":150000,"goodsCount":5}],"buyerIdCardNumber":"456"},"code":0}
            
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                printLog("查询成功:\(responseStr)")
                
                if let model = JDOrderDetailModel.deserialize(from: responseStr, designatedPath: "data") {
                    self.goodsDetailModel = model
                    var allGoodsPrice = 0.0
                    for goodsModel in model.goodsList ?? [JDOrderDetailGoodsModel]() {
                        allGoodsPrice = allGoodsPrice + JSON(goodsModel.salePrice as Any).doubleValue * JSON(goodsModel.goodsCount as Any).doubleValue
                    }
                    self.totalPriceLabel?.text = String.init(format: "￥%.2f", (allGoodsPrice + JSON(model.tariff as Any).doubleValue + JSON(model.freight as Any).doubleValue)/1000.00)
                    self.totalPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
                }
            }
            self.mainTableView?.reloadData()
            
        } failure: { error in
            printLog("查询失败:\(error)")
            
        } error: { errorCode in
            printLog("查询错误:\(errorCode)")
            
        }

    }

    func refreshByType() {
        if self.orderType == .waitingPay {
            // 待付款
        } else if self.orderType == .alreadyPay {
            // 已接单
            self.continuePaymentButton?.isHidden = true
            self.cancelButton?.isHidden = true
            self.totalPriceTitle?.text = "合计实付："
            self.totalPriceLabel?.text  = "￥0.00"
            self.totalPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
            
            self.tipsLabel?.isHidden = true
            self.tipsLabel?.snp.makeConstraints({ make in
                make.height.equalTo(0)
            })
        } else if self.orderType == .pickup {
            // 待取货
            self.continuePaymentButton?.isHidden = false
            self.continuePaymentButton?.setTitle("确认收货", for: .normal)
            self.cancelButton?.isHidden = true
            self.totalPriceTitle?.text = "合计实付："
            self.totalPriceLabel?.text  = "￥0.00"
            self.totalPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
            
            self.tipsLabel?.isHidden = true
            self.tipsLabel?.snp.makeConstraints({ make in
                make.height.equalTo(0)
            })
        } else if self.orderType == .completed {
            // 已完成
            self.continuePaymentButton?.isHidden = true
            self.cancelButton?.isHidden = true
            self.totalPriceTitle?.text = "合计实付："
            self.totalPriceLabel?.text  = "￥0.00"
            self.totalPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
            
            self.tipsLabel?.isHidden = true
            self.tipsLabel?.snp.makeConstraints({ make in
                make.height.equalTo(0)
            })
        } else if self.orderType == .refusse {
            // 已拒单
            self.continuePaymentButton?.isHidden = true
            self.cancelButton?.isHidden = true
            self.totalPriceTitle?.text = "合计实付："
            self.totalPriceLabel?.text  = "￥0.00"
            self.totalPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
            
            self.tipsLabel?.isHidden = true
            self.tipsLabel?.snp.makeConstraints({ make in
                make.height.equalTo(0)
            })
        }
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

    @objc func continuePayAction() {
        
        if self.orderType == .pickup {
            print("确认收货")
            self.showConfirmView("确认收到货了吗？") { [weak self] in
                var params = [String: Any]()
                params["orderId"] = self?.orderId

                JDNetWorkRequest(.confirmOrder(params)) { responseStr in
                                
                    let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                    if commonModel?.code == "0" {
                        JDTools.getKeyWindows()?.rootViewController?.view.toast(message: "确认收货成功")
//                        self?.view.toast(message: "确认收货成功")
                        NotificationCenter.default.post(name: NSNotification.Name("changeOrderIndex"), object: 3)
                        self?.navigationController?.popViewController(animated: true)
                    } else {
                        self?.view.toast(message: commonModel?.msg ?? "")
                    }
                } failure: { error in
                    self?.view.toast(message: error.localizedDescription)
                } error: { errorCode in
                    self?.view.toast(message: "网络异常")
                }
            }
        } else {
            var params = [String: Any]()
            params["orderNo"] = self.goodsDetailModel?.orderNo
                        
            JDNetWorkRequest(.doOrderPay(params)) { responseStr in
                
                let paymentMethodView = JDPaymentMethodView()
                paymentMethodView.priceLabel?.text = self.totalPriceLabel?.text
                paymentMethodView.priceLabel?.priceString(UIFont.systemFont(ofSize: 18, weight: .semibold), UIFont.systemFont(ofSize: 36, weight: .semibold))
                paymentMethodView.confirmButtonSelected = { [weak self] in
                    print("看看这个接口吧:\(responseStr)")
                    let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                    if commonModel?.code == "0" {
                        let alipayStr = JSON(commonModel?.data as Any).dictionaryValue["orderStr"]?.stringValue ?? ""
                        JDAlipayManager.pay(alipayStr)
                        paymentMethodView.removeFromSuperview()
                    }
                }
                paymentMethodView.wechatPayCallBack = { [weak self] in
                    
//                    微信支付吧
                    print("")
                    
                }
                                
                JDTools.getKeyWindows()?.rootViewController?.view.addSubview(paymentMethodView)

                
            } failure: { error in
                print("付款错误:\(error)")
                
            } error: { errorCode in
                print("付款异常code:\(errorCode)")
            }
        }
    }
    
    @objc func cancelOrderAction(_ button: UIButton) {
        
        self.showConfirmView("是否确认取消订单？") { [weak self] in
            self?.cancelOrderRequest()
        }
        
    }
    
    func cancelOrderRequest() {
        var params = [String: Any]()
        params["orderId"] = self.orderId

        JDNetWorkRequest(.cancelOrder(params)) { responseStr in

            printLog("删除成功:\(responseStr)")

            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                self.backAction()
                self.simpleCallBack?()
            }

        } failure: { error in

        } error: { errorCode in

        }
    }
    
}

extension JDOrderDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDOrderDetailCell
                
        cell?.orderType = self.orderType
        cell?.shopName = self.shopName
        cell?.goodsDetailModel = self.goodsDetailModel
        
        cell?.reloadData()
        
        cell?.logisticsInfoCallBack = {[weak self] sendId in
            print("这个是运单号:\(sendId)")
            let deliveryInfoVC = JDDeliveryInfoViewController()
            self?.hidesBottomBarPushViewController(deliveryInfoVC)
        }
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    
}
